import Vue from 'vue'
import Router from 'vue-router'
import { excludesRouterPath, tokenName } from '@/server/base.js'

Vue.use(Router)


export const constantRoutes = [
  {
    path: '/',
    redirect: '/layout/index/main'
  },
  {
    path: '/layout',
    name: 'layout',
    component: () => import('@/layout/index.vue'),
    children: [
      {
        path: 'index',
        name: 'index',
        component: () => import('@/views/home/index.vue'),
        children: [{
          path: 'main',
          name: 'main',
          component: () => import('@/views/home/main/index.vue'),
        }, {
          path: 'notice',
          name: 'notice',
          component: () => import('@/views/home/notice/index.vue'),
        }, {
          path: 'personal',
          name: 'personal',
          component: () => import('@/views/home/personal/index.vue'),
        }]
      },
      {
        path: 'other-page',
        name: 'other-page',
        component: () => import('@/views/home/main/other/index.vue'),
      },

      {
        path: 'login',
        name: 'login',
        component: () => import('@/views/login/index.vue')
      }
    ]
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/404.vue')
  },
  // 404 page must be placed at the end !!!
  { path: '*', redirect: '/404', hidden: true }
]





const createRouter = () => new Router({

  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

const router = createRouter()

router.beforeEach((to, form, next) => {
  if (!excludesRouterPath.includes(to.path)) {
    try {
      if (!localStorage.getItem(tokenName)) {
        next(`/layout/login?redirect=${to.path}`);
        return false;
      }

    } catch (e) {
      //ignore
    }
  } //判断跳转的是否是登录地址
  if (excludesRouterPath.includes(to.path) && localStorage.getItem(tokenName)) {
    next('/')
    return;
  }
  next();
})
// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router
